package org.massi.imslp.query;


import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import de.tudarmstadt.ukp.wikipedia.parser.ParsedPage;
import de.tudarmstadt.ukp.wikipedia.parser.Section;
import de.tudarmstadt.ukp.wikipedia.parser.Template;


/**
 * {@link ParsedPage} parser. Uses the visitor pattern to inspect the content of a
 * {@link ParsedPage} instance. it fires events when the parsing starts and ends, and when a
 * section, template or parameter is found
 * 
 * @see IParsedPageVisitor
 */
public class PageParser
{
	/**
	 * class logger
	 */
	private static final Logger LOG = Logger.getLogger(PageParser.class);


	/**
	 * Use the visitor pattern to parse the {@link ParsedPage}, and notify the listener
	 * 
	 * @param page the page to parse: must not be null
	 * @param visitor the visitor to notify: must not be null
	 */
	public void parse(final ParsedPage page, final IParsedPageVisitor visitor)
	{
		assert page != null;
		assert visitor != null;
		LOG.trace("Start ParsedPage parsing");
		visitor.onPageStart(page);
		final List<Section> sections = page.getSections();
		for (final Section section : sections)
		{
			visit(section, visitor);
		}
		LOG.trace("End ParsedPage parsing");
		visitor.onPageEnd(page);
	}


	/**
	 * Visit a section and notify the visitor
	 * 
	 * @param section
	 * @param visitor
	 */
	private void visit(final Section section, final IParsedPageVisitor visitor)
	{
		LOG.trace("Visiting section " + section);
		visitor.onSection(section);
		final List<Template> templates = section.getTemplates();
		for (final Template template : templates)
		{
			LOG.trace("Visiting template " + template);
			visitor.onTemplate(template);
			final List<String> parameters = template.getParameters();
			for (final String parameter : parameters)
			{
				final String key = StringUtils.trimToNull(StringUtils.substringBefore(parameter, "="));
				final String value = StringUtils.trimToNull(StringUtils.substringAfter(parameter, "="));
				LOG.trace("Found parameter [" + parameter + "]");
				if (key != null)
				{
					visitor.onParameter(key, value);
				}
			}
		}
	}


}
